package com.mive.service.impl;

import com.mive.entity.User;
import com.mive.mapper.UserMapper;
import com.mive.service.UserService;
import net.sf.ehcache.CacheException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Allen
 * @version 1.0.0
 * @createTime 2018-06-07 17:06
 * @description user
 */
@Service(value = "userService")
public class UserServiceImpl implements UserService {

    private static final String CACHE_KEY = "'user'";
    private static final String CACHE_NAME = "userCache";

    @Resource
    private UserMapper userMapper;

    @Override
    @CacheEvict(value = CACHE_NAME, key = "'user_'+#uuid")
    public void delete(String uuid) {
        this.userMapper.delete( uuid );
    }

    @Override
    @Cacheable(value = CACHE_NAME, key = "'user_'+#user.getUuid()")
    public User update(User user) throws CacheException{
        User user1 = userMapper.findByUuid(user.getUuid());
        if (null == user1){
            throw new CacheException("Not Find");
        }
        user1.setAge(user.getAge());
        user1.setName(user.getName());
        return user1;
    }

    @Override
    @Cacheable(value = CACHE_NAME, key = "'user_'+#uuid")
    public User findByUuid(String uuid) {
        //若找不到缓存将打印出提示语句
        System.err.println("没有走缓存！"+uuid);
        return userMapper.findByUuid( uuid );
    }

    @Override
    @CacheEvict(value = CACHE_NAME, key = CACHE_KEY)
    public int save(User user) {
        return userMapper.save( user );
    }

    @Override
    @Cacheable(value = CACHE_NAME, key = "'findAll'")
    public List<User> findAll() {
        return userMapper.findAll();
    }
}
